--
-- Author: shunguo.chen
-- Date: 2019-07-01 17:14:02
--
-- TeamMatchCrossPanel 组队跨服匹配panel
--

local AvatarIconNode = require("app.widget.AvatarIconNode")

local ClassRef = app.mvc.createPanelClass(...)

local NODE_MAX_GAP = 14

--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node)
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

function ClassRef:init(data)
    self.super.init(self, data)

    self._timeline = self:getTimeline(0)
    self._timeline:gotoFrameAndPlay(0, true)
    self:hide()

    local con = self._ui.Panel_ani
    local di = con:getChildByName("di")
    local mask = con:getChildByName("mask")
    mask:retain()
    mask:removeFromParent()
    di:retain()
    di:removeFromParent()

    local clipNode = cc.ClippingNode:create()
    clipNode:setContentSize(con:getContentSize())
    clipNode:setInverted(false)
    clipNode:setAlphaThreshold(0.5)
    clipNode:setStencil(mask)
    clipNode:addChild(di)
    clipNode:setName("di")
    con:addChild(clipNode, -1)

    di:release()
    mask:release()

    -- player heads
    local iconPanel = self._ui.Panel_icon
    local headNodes = {}
    local node
    for i=1,9 do
        node = iconPanel:getChildByName("icon_" .. i)
        node:setVisible(false)
        headNodes[i] = AvatarIconNode.new(node, "icon_img")
    end
    self._headNodes = headNodes
    self._headWidth = headNodes[1]:getContentSize2()
    self._panelWidth = iconPanel:getContentSize2()
end

function ClassRef:show()
    self:setVisible(true)
    self._timeline:resume()
end

function ClassRef:hide()
    self:setVisible(false)
    self._timeline:pause()
end

-- 有队伍就显示队伍信息，没有队伍就显示自己一个人的信息
-- data = TeamVo
function ClassRef:refresh()
    local team = self._data
    local baseInfos
    if team then
        baseInfos = team:getMemberBaseInfos()
    else
        baseInfos = {UD:getAvatarParams()}
    end

    for i,baseInfo in ipairs(baseInfos) do
        self._headNodes[i]:update(baseInfo)
    end
    self:_setHeadPos(#baseInfos)
end

function ClassRef:_setHeadPos(count)
    local allGap = self._panelWidth - count * self._headWidth
    local gap
    if allGap >= 0 then
        gap = allGap / count
    else
        gap = allGap / (count - 1)
    end
    gap = math.min(gap, NODE_MAX_GAP)

    local distance = gap + self._headWidth
    local startX
    if count % 2 == 0 then
        startX = self._panelWidth/2 - distance * (count-1) / 2
    else
        startX = self._panelWidth/2 - distance * math.floor(count / 2)
    end

    for i,headNode in ipairs(self._headNodes) do
        if i <= count then
            headNode:setPositionX(startX + (i-1) * distance)
            headNode:setVisible(true)
        else
            headNode:setVisible(false)
        end
    end
end

return ClassRef
